var timestamp =CurentTime();
jQuery.extend({
	
	 handleError: function( s, xhr, status, e ) 		{
	    	// If a local callback was specified, fire it
	    			if ( s.error ) {
	    				s.error.call( s.context || s, xhr, status, e );
	    			}

	    			// Fire the global callback
	    			if ( s.global ) {
	    				(s.context ? jQuery(s.context) : jQuery.event).trigger( "ajaxError", [xhr, s, e] );
	    			}
	    		},
	

    createUploadIframe: function(id, uri)
	{
			//create frame
            var frameId = 'jUploadFrame' + id;
            var iframeHtml = '<iframe id="' + frameId + '" name="' + frameId + '" style="position:absolute; top:-9999px; left:-9999px"';
			if(window.ActiveXObject)
			{
                if(typeof uri== 'boolean'){
					iframeHtml += ' src="' + 'javascript:false' + '"';

                }
                else if(typeof uri== 'string'){
					iframeHtml += ' src="' + uri + '"';

                }	
			}
			iframeHtml += ' />';
			jQuery(iframeHtml).appendTo(document.body);

            return jQuery('#' + frameId).get(0);			
    },
    createUploadForm: function(id, fileElementId, data)
	{
		//create form	
		var formId = 'jUploadForm' + id;
		var fileId = 'jUploadFile' + id;
		var form = jQuery('<form  action="" method="POST" name="' + formId + '" id="' + formId + '" enctype="multipart/form-data"></form>');	
		if(data)
		{
			for(var i in data)
			{
				jQuery('<input type="hidden" name="' + i + '" value="' + data[i] + '" />').appendTo(form);
			}			
		}
		var t = '';

if(typeof(fileElementId) == 'string'){

/*
04.
* 将传过来的值 如："file1,file2,file3" 转换为：['file1','file2','file3'] 
05.
*/

var s = fileElementId.split(",");

for(var i in s){

t = t +  "'"+s[i]+"'"+",";

}

t = "["+t+"]"; 

t = t.replace(",]", "]")
fileElementId= eval('('+ t +')'); //将string类型转换为Object类型
} 
for(var i in fileElementId){  
    var oldElement = jQuery('#' + fileElementId[i]);  
    var newElement = jQuery(oldElement).clone();  
    jQuery(oldElement).attr('id', fileId);  
    jQuery(oldElement).before(newElement);  
    jQuery(oldElement).appendTo(form);  
}

	/*	var oldElement = jQuery('#' + fileElementId);
		var newElement = jQuery(oldElement).clone();
		jQuery(oldElement).attr('id', fileId);
		jQuery(oldElement).before(newElement);
		jQuery(oldElement).appendTo(form);*/


		
		//set attributes
		jQuery(form).css('position', 'absolute');
		jQuery(form).css('top', '-1200px');
		jQuery(form).css('left', '-1200px');
		jQuery(form).appendTo('body');		
		return form;
    },

    ajaxFileUpload: function(s) {
        // TODO introduce global settings, allowing the client to modify them for all requests, not only timeout		
        s = jQuery.extend({}, jQuery.ajaxSettings, s);
        var id = new Date().getTime();        
		var form = jQuery.createUploadForm(id, s.fileElementId, (typeof(s.data)=='undefined'?false:s.data));
		var io = jQuery.createUploadIframe(id, s.secureuri);
		var frameId = 'jUploadFrame' + id;
		var formId = 'jUploadForm' + id;		
        // Watch for a new set of requests
        if ( s.global && ! jQuery.active++ )
		{
			jQuery.event.trigger( "ajaxStart" );
		}            
        var requestDone = false;
        // Create the request object
        var xml = {}   
        if ( s.global )
            jQuery.event.trigger("ajaxSend", [xml, s]);
        // Wait for a response to come back
        var uploadCallback = function(isTimeout)
		{			
			var io = document.getElementById(frameId);
            try 
			{				
				if(io.contentWindow)
				{
					 xml.responseText = io.contentWindow.document.body?io.contentWindow.document.body.innerHTML:null;
                	 xml.responseXML = io.contentWindow.document.XMLDocument?io.contentWindow.document.XMLDocument:io.contentWindow.document;
					 
				}else if(io.contentDocument)
				{
					 xml.responseText = io.contentDocument.document.body?io.contentDocument.document.body.innerHTML:null;
                	xml.responseXML = io.contentDocument.document.XMLDocument?io.contentDocument.document.XMLDocument:io.contentDocument.document;
				}						
            }catch(e)
			{
				jQuery.handleError(s, xml, null, e);
			}
            if ( xml || isTimeout == "timeout") 
			{				
                requestDone = true;
                var status;
                try {
                    status = isTimeout != "timeout" ? "success" : "error";
                    // Make sure that the request was successful or notmodified
                    if ( status != "error" )
					{
                        // process the data (runs the xml through httpData regardless of callback)
                        var data = jQuery.uploadHttpData( xml, s.dataType );    
                        // If a local callback was specified, fire it and pass it the data
                        if ( s.success )
                            s.success( data, status );
    
                        // Fire the global callback
                        if( s.global )
                            jQuery.event.trigger( "ajaxSuccess", [xml, s] );
                    } else
                        jQuery.handleError(s, xml, status);
                } catch(e) 
				{
                    status = "error";
                    jQuery.handleError(s, xml, status, e);
                }

                // The request was completed
                if( s.global )
                    jQuery.event.trigger( "ajaxComplete", [xml, s] );

                // Handle the global AJAX counter
                if ( s.global && ! --jQuery.active )
                    jQuery.event.trigger( "ajaxStop" );

                // Process result
                if ( s.complete )
                    s.complete(xml, status);

                jQuery(io).unbind()

                setTimeout(function()
									{	try 
										{
											jQuery(io).remove();
											jQuery(form).remove();	
											
										} catch(e) 
										{
											jQuery.handleError(s, xml, null, e);
										}									

									}, 100)

                xml = null

            }
        }
        // Timeout checker
        if ( s.timeout > 0 ) 
		{
            setTimeout(function(){
                // Check to see if the request is still happening
                if( !requestDone ) uploadCallback( "timeout" );
            }, s.timeout);
        }
        try 
		{

			var form = jQuery('#' + formId);
			jQuery(form).attr('action', s.url);
			jQuery(form).attr('method', 'POST');
			jQuery(form).attr('target', frameId);
            if(form.encoding)
			{
				jQuery(form).attr('encoding', 'multipart/form-data');      			
            }
            else
			{	
				jQuery(form).attr('enctype', 'multipart/form-data');			
            }			
            jQuery(form).submit();

        } catch(e) 
		{			
            jQuery.handleError(s, xml, null, e);
        }
		
		jQuery('#' + frameId).load(uploadCallback	);
        return {abort: function () {}};	

    },

    uploadHttpData: function( r, type ) {
        var data = !type;
        data = type == "xml" || data ? r.responseXML : r.responseText;
        // If the type is "script", eval it in global context
        if ( type == "script" )
            jQuery.globalEval( data );
        // Get the JavaScript object, if JSON is used.
        if ( type == "json" )
        	  ////////////以下为新增代码///////////////  
            data = r.responseText;  
            var start = data.indexOf(">");  
            if(start != -1) {  
              var end = data.indexOf("<", start + 1);  
              if(end != -1) {  
                data = data.substring(start + 1, end);  
               }  
            }  
             ///////////以上为新增代码///////////////  
             eval( "data = " + data);  
        if ( type == "html" )
            jQuery("<div>").html(data).evalScripts();

        return data;
    }

});



/**
	 * 添加图片
	 * 
	 * id 上传图片的file的id；
	 * type 图片类型
	 * 
	 */
  function uploadImg(id,type){
	  	var $this = $("#"+id); /// 点击的对象 
	  	var imageFile =$this.attr("id");
	  	var imageUrl =$this.siblings("input:hidden");
	  	var a=$this.parent().find('a');
	  	var img=$this.parent().find('img');
	  	var i = $this.parent().find('i');
	  	var isMid= $("#isMid").val();
		var orgCodes= $("#orgCodes").val();
		var url=$("url").val();
		 var flag=fileInfo(imageFile);
		 if(flag){
	      $.ajaxFileUpload({  
	        fileElementId: imageFile,  
	        url: '/fmposm/upload/uploadImage.ct',  // '<c:url value="/pages/uploadImage.action"/>'
	        dataType: 'json',  
	        data: { isMid:isMid,"type":type,"orgCodes":orgCodes}, 
	        beforeSend: function (XMLHttpRequest) { 
	        },  
	        success: function (data, textStatus) {  
	   			var statusCode = data.statusCode;
	   			if(statusCode=="success"){
	   				 
	   				var name=encodeURI(data.date);//alert(name);
	   				var url="http://"+window.location.host+"/fmposm/upload/showImg.ct?orgs="+orgCodes+"&mid="+name;
//	   				var url="http://shoudan.freemypay.com:18090/fmposm/upload/showImg.ct?orgs="+orgCodes+"&mid="+name;
	   				url=encodeURI(url);
	   				/*alert(url);
	   				$("#qwe").attr("src",url);*/
	   				img.attr("src",url+"&time="+new Date().getTime());
		        	a.attr("href",url+"&time="+new Date().getTime());
		        	imageUrl.val(url+"&time="+new Date().getTime());
	   				//img.attr("src",data.date+"?time="+new Date().getTime());
		        	//a.attr("href",data.date+"?time="+new Date().getTime());
		        	//imageUrl.val(data.date);
		        	 $("#div"+imageFile.split("img")[1]).find("label").html("");
		        	 $("#div"+imageFile.split("img")[1]).find("code").html("");
		        	a.css("display","block"); 
		        	i.show();
	   			}else{
	   				alert("上传失败");
	   			}
	        },  
	        error: function (XMLHttpRequest, textStatus, errorThrown) {  
	        	alert("上传失败");
	        },  
	        complete: function (XMLHttpRequest, textStatus) {  
	          //("loaded");  
	        }  
	      });  
		 }
   }  
  /**
   * 获取当前日期 格式 YYYYMMDDHH
   * @returns
   */
  
  var clock ;
  
  function CurentTime()
  { 
      var now = new Date();
      
      var year = now.getFullYear();       //年
      var month = now.getMonth() + 1;     //月
      var day = now.getDate();            //日
      
      var hh = now.getHours();            //时
      var mm = now.getMinutes();          //分
      var ss = now.getSeconds();           //秒
      
       clock = year ;
      
      if(month < 10)
          clock += "0";
      
      clock += month;
      
      if(day < 10)
          clock += "0";
          
      clock += day ;
      
      if(hh < 10)
          clock += "0";
          
      clock += hh;
      if (mm < 10)
      	clock += '0'; 
      clock += mm ; 
       
     /* if (ss < 10) clock += '0'; 
      clock += ss; */
      return(clock); 
  }
  
  /**
	 * 添加图片（变更信息）
	 * 
	 * id 上传图片的file的id；
	 * type 图片类型
	 * 
	 */
function uploadChangeImg(id,type){
	  	var $this = $("#"+id); /// 点击的对象 
	  	var imageFile =$this.attr("id");
	  	var imageUrl =$this.siblings("input:hidden");
	  	var a=$this.parent().find('a');
	  	var img=$this.parent().find('img');
	  	var i = $this.parent().find('i');
	  	var isMid= $("#isMid").val();
		var orgCodes= $("#orgCodes").val();
		var url=$("url").val();
		var changeType= $("#merinfoChangeTyep").val();
//		var timestamp =CurentTime();
//		alert(timestamp);
		 var flag=fileInfo(imageFile);
		 if(flag){
	      $.ajaxFileUpload({  
	        fileElementId: imageFile,  
	        url: '/fmposm/upload/uploadChangeImage.ct',  // '<c:url value="/pages/uploadImage.action"/>'
	        dataType: 'json',  
	        data: { isMid:isMid,
	        	"type":type,
	        	"orgCodes":orgCodes,
	        	"changeType":changeType,
	        	"timestamp":timestamp
	        	}, 
	        beforeSend: function (XMLHttpRequest) { 
	        },  
	        success: function (data, textStatus) {  
	   			var statusCode = data.statusCode;
	   			if(statusCode=="success"){
	   				 
	   				var name=encodeURI(data.date);//alert(name);
	   				//var url="http://"+window.location.host+"/fmposm/upload/showImg.ct?orgs="+orgCodes+"&mid="+name;
	   				var url="http://shoudan.freemypay.com:18090/fmposm/upload/showImg.ct?orgs="+orgCodes+"&changeType="+changeType+"&timestamp="+timestamp+"&mid="+name;
	   				url=encodeURI(url);
	   				/*alert(url);
	   				$("#qwe").attr("src",url);*/
	   				img.attr("src",url+"&time="+new Date().getTime());
		        	a.attr("href",url+"&time="+new Date().getTime());
		        	imageUrl.val(url+"&time="+new Date().getTime());
	   				//img.attr("src",data.date+"?time="+new Date().getTime());
		        	//a.attr("href",data.date+"?time="+new Date().getTime());
		        	//imageUrl.val(data.date);
		        	 $("#div"+imageFile.split("img")[1]).find("label").html("");
		        	 $("#div"+imageFile.split("img")[1]).find("code").html("");
		        	a.css("display","block"); 
		        	i.show();
	   			}else{
	   				alert("上传失败");
	   			}
	        },  
	        error: function (XMLHttpRequest, textStatus, errorThrown) {  
	        	alert("上传失败");
	        },  
	        complete: function (XMLHttpRequest, textStatus) {  
	          //("loaded");  
	        }  
	      });  
		 }
 }  


  
  function fileInfo(fileId) {  
	  if( typeof(fileId)!="undefined"  &&fileId!=null&& fileId!=0){
		  var file= document.getElementById(fileId).files; 
	      //var src= file[0].type;
	      var src=file[0].name;
	      var type=(src.substr(src.lastIndexOf("."))).toLowerCase();
	      if(type!=".jpg"&& type!=".png"&& type!=".gif"){
	    	 alert("您上传图片的类型不符合(.jpg|.png|.gif)！");
	    	 return false;
	      }
	      var sizes=file[0].size;
	 	  var maxsize = 3 * 1024 * 1024;
		  if(sizes>parseInt(maxsize)){
			 alert("上传图片必须小于3M");
			 return false;
		  } 
	  }else{
		  alert("请上传图片");
			 return false;
	  }
	  return true;
  }  

 /* //拍照上传
  function preImg(id,imgPreThree) {
	  $.ajaxFileUpload({  
	        fileElementId: id,  
	        url: '/fmposm/pages/uploadImage.ct',  // '<c:url value="/pages/uploadImage.action"/>'
	        dataType: 'json',  
	       // data: { id: a }, 
	        beforeSend: function (XMLHttpRequest) { 
	        },  
	        success: function (data, textStatus) {  
	   			var statusCode = data.statusCode;
	   			if(statusCode=="success"){
		        	img.attr("src",data.date);
		        	a.attr("src",data.date);
		        	imageUrl.val(data.date);
		        	a.css("display","block");
		        	i.show();
	   			}else{
	   				alert("上传失败");
	   			}
	        },  
	        error: function (XMLHttpRequest, textStatus, errorThrown) {  
	        	alert("上传失败");
	        },  
	        complete: function (XMLHttpRequest, textStatus) {  
	          //("loaded");  
	        }  
	      });  
		 }
 
  //拍照上传 end
  */
  
		/**
		 * 删除图片
		 */
  function deleteImage(){ 
	/*  var deleteUrl =$("#"+imageUrl).val();*/
	  var $this = $(this); /// 点击的对象
      $this.hide();
      $this.siblings('a').hide();
      var imageUrl =$this.siblings("input:hidden");
      imageUrl.val("");
  	var a=$this.parent().find('a');
  	a.removeAttr("href");
  	var img=$this.parent().find('img');
  	img.removeAttr("src");
      $("#clickInp").val("");
/*	  $.ajax({
		   type: "POST",
		   url: '/WXYX/pages/deleteImage.action',// '<c:url value="/pages/deleteImage.action"/>'
		   dataType: 'json',  
	       data: { deleteUrl: deleteUrl },  
		   success: function(msg){
			   var statusCode = msg.statusCode;
	   			if(statusCode=="success"){
				    $("#"+imageImg).attr("src","/WXYX/images/addimage.png");//<s:url value='/images/addimage.png'/>
		        	$("#"+imageUrl).val("");
		        	$("#"+imageFile).css("display","block"); 
		        	$("#"+deleteImg).css("display","none"); 
		        	if( typeof(domain)!="undefined"  &&domain!=null&& domain!=0){
		        		$("#"+domain).val("");
		        	}
	   			}else{
	   				alert("删除失败");
	   			}
		   }
		});*/
	  
	
    }  



